package july.framework.exsolver.factory.impl;

import july.framework.exsolver.bean.Resolver;
import july.framework.exsolver.handler.ResolversHandler;
import july.framework.exsolver.demo.eao.BankResolverEAO;
import july.framework.exsolver.executor.ResolveExcutor;
import july.framework.exsolver.factory.ProxyFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class DefaultProxyFactory<T> implements ProxyFactory<T> {

    private Class<T> target;

    public DefaultProxyFactory(Class<T> target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        // 获取类名和方法名，并从mapper缓存中获取mapper实例
        String interfaceName = target.getName();
        String methodName = method.getName();
        String key = interfaceName + "." + methodName;

         // 进行内容解析,返回解析结果
        Resolver resolver = ResolversHandler.get(key);
        Class returnType = Class.forName(resolver.getReturnType());
        ResolveExcutor executor = new ResolveExcutor(resolver);

        return executor.execute(returnType, args[0].toString());
    }

    @Override
    public T createProxy() {
        T targetProxy = (T)Proxy.newProxyInstance(target.getClassLoader(), new Class[]{target}, this);
        return targetProxy;
    }

}
